Day14 要來學習怎麼複製資料
let age = 100;
let age2 = age;
age = 200;
let name = "Wes";
let name2 = name;
name = "wesley";
team
與 players
指向相同,所以會更動到原始的陣列 const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
const team: string[] = players;
team[3] = "Lux";
slice()
會回傳新的陣列,所以不會更動到原始資料 const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
const team2: string[] = players.slice();
team2[3] = "Copy 1";
concat()
連接起來也可以複製陣列 const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
const team3: string[] = ([] as string[]).concat(players);
team3[3] = "Copy 2";
const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
const team4: string[] = [...players];
team4[3] = "Copy 3";
Array.from()
可以複製陣列 const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
const team5: string[] = Array.from(players);
team5[3] = "Copy 4";
Object.assign()
來建立新的物件,然後用來包裝原始資料與新的資料 const person: Person = { name: "Wes Bos", age: 80 };
const cap2: Person = Object.assign({}, person, { number: 99, age: 12 });
JSON.parse(JSON.stringify(data)
const wes: Wes = {
name: "Wes",
age: 100,
social: {
twitter: "@wesbos",
facebook: "wesbos.developer",
},
};
const dev2: Wes = JSON.parse(JSON.stringify(wes));
dev2.social.twitter = "@wesdev";
https://codesandbox.io/p/devbox/day14-javascript-references-vs-copying-7gtntz